﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows.Threading;
using BlueCrestStudio.DataVirtualization.Client.StockDataService;

namespace BlueCrestStudio.DataVirtualization.Client.ViewModels
{
    public class StockXamGridViewModel : INotifyPropertyChanged 
    {
        private readonly IItemsProvider<Stock> _dataProvider;
        private string _memoryUsage;
        public string MemoryUsage
        {
            get { return _memoryUsage; }
            set
            {
                _memoryUsage = value;
                OnPropertyChanged("MemoryUsage");
            }
        }

        public VirtualizingCollection<Stock> Items { get; set; }
        
        public StockXamGridViewModel(IItemsProvider<Stock> dataProvider)
        {
            _dataProvider = dataProvider;
            // use a timer to periodically update the memory usage
            var timer = new DispatcherTimer {Interval = new TimeSpan(0, 0, 1)};
            timer.Tick += timer_Tick;
            timer.Start();

            Items = new VirtualizingCollection<Stock>(dataProvider, 1000);
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            MemoryUsage = string.Format("{0:0.00} MB", GC.GetTotalMemory(true) / 1024.0 / 1024.0);
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
